<?php

abstract class AbstractAjaxHandler {

	protected function getOkMessage() { return "'[OK]'"; }

	protected $arrServiceMethods;
	protected $arrAllMethods;

	public function __construct() {	}

	public function tryHandleCommand($cmd) {

		try {

			Output::plaintextHeader();

			$cmd = strtolower($cmd);
			$arrServiceMethods = get_class_methods(get_class());
			$arrAllMethods = get_class_methods($this);

			if ( in_array($cmd, $arrAllMethods) &&
				!in_array($cmd, $arrServiceMethods)
			) {
				echo $this->$cmd();
			} else {
				echo $this->defaultResponse($cmd);
			}

		} catch (Exception $e) {
		    throw new AjaxHandlerException($e);
//			echo "<h2>ERROR:</h2>";
//			echo "<pre>". $e->__toString() . "</pre>";
		}
	}

	protected function defaultResponse($cmd) {
		return "unknown command [$cmd] for " . get_class($this) . ' on ' . Url::createCurrent()->composeLinkOnSite();
	}

	protected function outputAsText($content) {
		echo $content;
	}

	protected function getFormattedMultilineError(array $arrErrors) {
		return '<ul><li>' . implode('</li><li>', $arrErrors) . '</li></ul>';
	}

	public function isNull() { return false; }
}

class AjaxHandlerException extends Exception {
    private $e;
    public function __construct(Exception $e) { $this->e = $e; }
    public function __toString() { return $this->e->__toString(); }
}

?>